<template>
  <a-divider
    v-if="formItemConfig.type === 'divider'"
    orientation="left"
    dashed
    v-bind="formItemConfig.props"
    >{{ formItemConfig.label }}</a-divider
  >
  <span
    v-else-if="formItemConfig.type === 'text'"
    v-bind="formItemConfig.props"
    >{{ value }}</span
  >
  <a-form-item
    v-else
    :key="formItemConfig.key"
    :label="formItemConfig.label"
    :name="formItemConfig.key"
    :rules="finalRules"
    :style="formItemConfig.type === 'table' ? { flexWrap: 'nowrap' } : {}"
  >
    <component
      :is="compMap[formItemConfig.type] || 'a-' + formItemConfig.type"
      :style="{ width: '100%' }"
      autocomplete="off"
      v-model:value.trim="value"
      :placeholder="`${formItemConfig.type === 'select' ? '请选择' : '请填写'}${
        formItemConfig.label
      }`"
      :allowClear="true"
      v-bind="formItemConfig.props"
      :disabled="onlyRead"
    />
  </a-form-item>
</template>
<script lang="ts" setup>
import { computed } from "vue";
import { compMap } from "./config";
import { RuleObject } from "ant-design-vue/es/form/interface";
const props = defineProps<{
  formItemConfig: FormItem;
  formState: any;
  onlyRead?: boolean;
  rules?: Record<string, RuleObject>;
}>();
import { useHtmlToText } from "@/store";
const { convert } = useHtmlToText();
const emit = defineEmits<{ (event: "update:formState", value: any): void }>();
const value = computed({
  get() {
    return props.formState;
  },
  set(val) {
    const res =
      typeof val === "string" &&
      props.formItemConfig?.props?.type !== "password"
        ? val.trim()
        : val;
    emit("update:formState", res);
  },
});
const finalRules = computed(() => {
  const { rules, formItemConfig } = props;
  let res: any = rules?.[formItemConfig.key || ""];
  if (res) return res;
  if (!res && formItemConfig.type === "editor") {
    return [
      {
        required: true,
        validator: (rule: any, value: string) => {
          if (value === "") {
            return Promise.reject(`${formItemConfig.label}必填`);
          } else if (!convert(value).trim()) {
            return Promise.reject(`${formItemConfig.label}必填`);
          }
          return Promise.resolve();
        },
      },
    ];
  }
  res =
    formItemConfig.required === false
      ? undefined
      : [
          {
            required: true,
            message: `${formItemConfig.label}必填`,
          },
        ];
  return res;
});
</script>
<style lang="scss" scoped></style>
